<template>
  <div class="main_con"
       v-loading="loading"
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)"
  >

    <div style="text-align: left;display: flex;align-items: center">
      <H2>值班表</H2>
      <el-date-picker
          class="ml-5"
          style="margin-left: 15px"
          v-model="selectedDate"
          type="month"
          @change="dateChangeHandler"
          value-format="yyyy-MM"
          format="yyyy-MM"
          placeholder="请选择月份">
      </el-date-picker>
      <el-button @click="generateSchedule" :disabled="list.length > 0" style="margin-left: 5px" type="primary">自动生成排班表</el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          :title="'确定删除' + selectedDate + '月值班表吗？'"
          @confirm="deleteSchedule"
      >
        <el-button type="danger" slot="reference">删除值班表 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>

    <el-calendar v-model="selectedDate">
      <template slot="dateCell" slot-scope="{date, data}">
        <div style="display: flex;justify-content: center">
          <div style="width: 100%;display: flex;justify-content: center">
            <div style="margin-right: 5px">
              {{ data.day.split('-').slice(1).join('-') }}
            </div>
            <div v-if="list" style="" v-for="(item,index) in list" :key="index">
              <el-tag type="success" v-if="item.date === data.day && !(item.dayTypeId >1 && item.dayTypeId <7) && item.shiftId === 3">{{item.dayTypeName}}</el-tag>
            </div>
          </div>
        </div>

        <div v-if="list" style="width:100%;display: flex;flex-direction: column;align-items: center" v-for="(item,index) in list" :key="index">
          <!-- 先渲染上午和下午 -->
          <el-tag @click="editDialogOpenHandler(item)" class="atHover" style="margin-top: 6px" :type="(item.dayTypeId>1 && item.dayTypeId < 7) ? 'primary' : 'danger' " v-if="item.date === data.day && item.shiftId === 1">
            上午:{{ item.person }}<i class="el-icon-edit"></i>
          </el-tag>
          <el-tag @click="editDialogOpenHandler(item)" class="atHover"  style="margin-top: 10px" :type="(item.dayTypeId>1 && item.dayTypeId < 7) ? 'primary' : 'danger' " v-if="item.date === data.day && item.shiftId === 2">下午：{{ item.person }}<i class="el-icon-edit"></i></el-tag>
          <!-- 最后渲染夜班 -->
          <el-tag @click="editDialogOpenHandler(item)" class="atHover" style="margin-top: 10px" :type="item.dayTypeId === 6 &&item.shiftId === 3 ? 'danger' :(item.dayTypeId>1 && item.dayTypeId < 6) ? 'primary' : 'danger' " v-if="item.date === data.day && item.shiftId === 3">夜班：{{ item.person }}<i class="el-icon-edit"></i></el-tag>
        </div>
      </template>
    </el-calendar>
    <el-dialog :title="form.date + '----' +form.dayTypeName + '----' + form.person" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
      <el-form label-width="120px" size="small" style="width: 80%; margin: 0 auto">
        <el-form-item label="日期">
          <el-input disabled v-model="form.date" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input disabled v-model="form.dayTypeName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班次">
          <el-tag :type="form.shiftId === 3 ? 'danger' : 'primary'">{{form.shiftId === 1 ? '上午' : form.shiftId === 2 ? '下午' : '夜班' }}</el-tag>
        </el-form-item>
        <el-form-item label="值班人">
          <el-select filterable  v-model="form.personId" filterable placeholder="请选择">
            <el-option
                v-for="item in personList"
                :key="item.personId"
                :label="item.realName"
                :value="item.personId">
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.shiftCount }}次值班</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";

export default {
  name: "Schedule",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      form: {},
      dialogFormVisible: false,
      multipleSelection: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      uploadHeaders: {"token": localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")).token : ''},
      list: [],
      personList:[],
      selectedDate:dayjs().format('YYYY-MM'),
      loading:false,
    }
  },
 async mounted() {
    await this.load()


  },
  methods:{
    deleteSchedule(){
      this.request.delete("/schedule/deleteSchedule/"+this.selectedDate).then(res => {
        if(res.code === '0'){
          this.$message.success("删除成功")
          this.load()
        }else {
          this.$message.error("删除失败")
        }
      })
    },
    generateSchedule(){
      this.loading = true
      this.request.get("/schedule/generateSchedule",{
        params:{
          date:this.selectedDate
        }
      }).then(res => {
        if(res.code === '0'){
          this.$message.success("生成成功")
          const shift1 = this.list.filter(item => item.shiftId === 1)
          const shift2 = this.list.filter(item => item.shiftId === 2)
          const shift3 = this.list.filter(item => item.shiftId === 3)
          this.list = shift1.concat(shift2).concat(shift3)
          this.load()
          this.loading = false

        }else {
          this.$message.error("生成失败")
          this.loading = false
        }
      })
    },
    dateChangeHandler(){
      this.load()
    },
    getPersonList(){
      let gender   = null;
      if (this.form.shiftId === 3){
        gender = 1
      }else {
        gender = 2
      }
      return new Promise((resolve, reject) => {
        this.request.get("/schedule/getPersonList",{
          params:{
            gender:gender,
            dayTypeId:this.form.dayTypeId
          }
        }).then(res => {
          this.personList = res.data
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    save(){
      this.form.shiftDate = this.form.date
      this.request.post("/schedule",this.form).then(res => {
        if (res.code === '0'){
          this.dialogFormVisible = false
          this.load()
          this.$message.success("修改成功")
        }else {
          this.$message.error("修改失败")
        }
      })
    },
   async editDialogOpenHandler(item){
      this.form = JSON.parse(JSON.stringify(item));
      await this.getPersonList()
      this.dialogFormVisible = true
    },

    load(){
      return new Promise((resolve, reject) => {
        this.request.get("/schedule/querySchedule",{
          params:{
            date:this.selectedDate
          }
        }).then(res => {
          if (res.data.length > 0){
            this.list = res.data
            const shift1 = this.list.filter(item => item.shiftId === 1)
            const shift2 = this.list.filter(item => item.shiftId === 2)
            const shift3 = this.list.filter(item => item.shiftId === 3)
            this.list = shift1.concat(shift2).concat(shift3)
            resolve()
          }else {
            this.list = []
            this.$message.error("当前没有排班信息，请先排班")
            resolve()
          }
        }).catch(res => {
          reject(res)
        })
      })
    }
  }
}
</script>


<style scoped>
/deep/ .el-calendar-day  {
  box-sizing: border-box;
  padding: 5px;
  height: 140px;
}
/deep/ .el-button-group{
  display: none;
}
.atHover:hover{
  transform: scale(1.2);
}

</style>
